package com.platform.modules.mall.activity.type;

import com.platform.modules.mall.entity.MallGoodsToActivityEntity;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;
import java.util.Random;


@Scope(value = "request", proxyMode = ScopedProxyMode.TARGET_CLASS)
@Component
public class DrawGoodsType extends ActivityTypeAbstract{

    private BigDecimal countNum=new BigDecimal("0");

    @Override
    public void setEntity(List<MallGoodsToActivityEntity> entityList) {
        super.setEntity(entityList);
        entityList.forEach(x->countNum=countNum.add(x.getProbability()));
    }

    @Override
    public void delEntity(MallGoodsToActivityEntity entity) {
        super.delEntity(entity);
        countNum=countNum.subtract(entity.getProbability());
    }

    @Override
    public MallGoodsToActivityEntity getEntity() {
        /*没有商品可以抽了，直接返回null*/
        if (CollectionUtils.isEmpty(entityList)){
            return null;
        }
        /*生成随机数*/
        int num = new Random().nextInt(countNum.intValue())+1;
        BigDecimal count=new BigDecimal("0");
        BigDecimal ling = new BigDecimal("0");
        for (MallGoodsToActivityEntity entity:entityList) {

            /*中奖概率为0不参与抽奖*/
            if (ling.compareTo(entity.getProbability())!=-1){
                continue;
            }
            /*计算该商品的中奖范围*/
            count=count.add(entity.getProbability());
            /*查看随机数值是否在中奖范围内，在范围内说明中奖*/
            if (num<=count.intValue()){
                return entity;
            }
        }
        return null;
    }
}
